package ch.simplix.android.digest;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * This class helps to digest one-way-function any message.
 * It can be done with MD5 or with SHA-1.
 * 
 * It is equivalent to the function sha1sum in linux.
 * 
 * @author reto
 *
 */
public class DigestHelper{
	public static BigInteger getMD5(String message){
		BigInteger messageDigest=null;
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");		
		digest.update(message.getBytes());
		messageDigest=new BigInteger(1,digest.digest());
		
		} catch (NoSuchAlgorithmException e) {
			//Not possible
		}
		return messageDigest;		 
	}
	public static BigInteger getSHA1(String message){
		BigInteger messageDigest=null;
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");		
		digest.update(message.getBytes());
		messageDigest=new BigInteger(1,digest.digest());
		
		} catch (NoSuchAlgorithmException e) {
			//Not possible
		}
		return messageDigest;		 
	}
	
	public static String byteToString(byte[] b) {
		StringBuffer s = new StringBuffer();
		if(b==null) return s.toString();
		for (int i = 0; i < b.length; i++) {
			int d = b[i];
			d += d < 0 ? 256 : 0;
			// byte 128-255
			if (d < 16) {
				// 0-15 16
				s.append("0");
			}
			s.append(Integer.toString(d, 16));
		}
		return s.toString();
	}
	public static boolean isEqual(String message,BigInteger messageDigest){
		return getMD5(message).equals(messageDigest)||getSHA1(message).equals(messageDigest);
	}
	
}
